package com.yupi.generator;


import com.yupi.model.MainTemplateConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 动态代码生成器
 */
public class DynamicGenerator {
    public static void main(String[] args) throws IOException, TemplateException {
        // 当前idea打开的窗口，指定父级目录
        String projectPath = System.getProperty("user.dir")+File.separator+"yuzi-generator-basic";
        String inputPath = projectPath + File.separator + "src/main/resources/templates/MainTemplate.java.ftl";
        String outputPath = projectPath + File.separator + "MainTemplate2.java";
        MainTemplateConfig mainTemplateConfig = new MainTemplateConfig();
        // 这次使用循环
        mainTemplateConfig.setLoop(true);
        mainTemplateConfig.setAuthor("cjj");
        mainTemplateConfig.setOutputText("求和结果：");
        doGenerate(inputPath,outputPath,mainTemplateConfig);

    }

    /**
     *
     *将生成模版逻辑层封装成方法，支持动态调用
     * @param inputPath
     * @param outputPath
     * @param model
     * @throws IOException
     * @throws TemplateException
     */
    public static void doGenerate(String inputPath,String outputPath , Object model) throws IOException, TemplateException {

//       new出 Configuration 对象，参数为 FreeMarker 版本号
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_32);

//      指定模版所在目录
        File templateDir = new File(inputPath).getParentFile();
        configuration.setDirectoryForTemplateLoading(templateDir);


//      设置模板文件使用的字符集
        configuration.setDefaultEncoding("utf-8");
        configuration.setNumberFormat("0.######");


//       创建模板对象，加载指定模板
        String templateName = new File(inputPath).getName();
        Template template = configuration.getTemplate(templateName,"utf-8");



//      定义生成模板所在目录
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(Paths.get(outputPath)), StandardCharsets.UTF_8));
        template.process(model,out);

        //关闭流
        out.close();
    }

}
